<template>
  <div class="function-point-container">
    <!-- 批量导入 -->
    <el-upload
      ref="uploadXlsx"
      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
      action
      :auto-upload="false"
      :on-change="importData"
      :on-remove="handleRemove"
      :file-list="fileUploadList"
    >
      <el-button type="primary">文件上传</el-button>
    </el-upload>
  </div>
</template>
  
  <script>
import * as XLSX from "xlsx";
export default {
  name: "FunctionPoint",
  props: {
    modelList: {
      type: Array,
      default: [],
    },
  },
  data() {
    return {
      list: [],
      fileUploadList: [],
    };
  },
  created() {},
  methods: {
    // 批量导入
    importData(file, fileList) {
      this.list = this.modelList;
      console.log(file, fileList, "file wen");
      let testFile = file.name
        .substring(file.name.lastIndexOf(".") + 1)
        .toLowerCase();
      const extension = testFile === "xlsx" || testFile === "xls";
      let fileSize = Number(file.size / 1024 / 1024);
      if (!extension) {
        this.$message({
          message: "上传文件只能是xls/xlsx!",
          type: "warning",
        });
        this.$refs.uploadXlsx.uploadFiles.pop();
        return false;
      }
      if (fileSize > 5) {
        fileList=fileList.pop();
        console.log(fileList,'fileList================')
        this.$message({
          message: "文件大小不能超过5M！",
          type: "warning",
        });
        return false;
      }
      console.log(222222222222222222222222222222222222222222)
      // 拿取文件对象
      const f = file.raw;
      console.log(f, file, "33333333");
      // 用 FileReader 来读取
      let reader = new FileReader();
      // 重写 FileReader 上的 readAsBinaryString 方法
      FileReader.prototype.readAsBinaryString = (f) => {
        let binary = "";
        let wb; // 读取完成的数据
        let outdata; // 你需要的数据
        let reader = new FileReader();
        reader.onload = (e) => {
          // 读取成Uint8Array，再转换为Unicode编码（Unicode占两个字节）
          let bytes = new Uint8Array(reader.result);
          let length = bytes.byteLength;
          for (let i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          // 接下来就是xlsx了，具体可看api
          wb = XLSX.read(binary, {
            type: "binary",
            cellDates: false,
          });
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
          const result = this.generateParam(outdata);
          result.map((val) => {
            this.$set(val, "tableName", f.name);
          });
          console.log("result--", result);
          this.list = [...this.list, ...result];
          console.log(this.list, "this.list");
          this.$emit("batchData", this.list);
          // 下面就进行接口调用了...
        };
        reader.readAsArrayBuffer(f);
      };
      reader.readAsBinaryString(f);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.list = this.list.filter((item) => item.tableName != file.name);
      this.$emit("batchData", this.list);
    },
    // 生成导入参数
    generateParam(data) {
      const params = [];
      // 这里根据实际表格 title 值、接口参数值，灵活变化
      const parse = {
        品牌: "brand",
        优势型号: "partNumber",
        备注: "remark",
      };
      data.forEach((item) => {
        let obj = {};
        const keys = Object.keys(parse);
        const itemKeys = Object.keys(item);
        itemKeys.forEach((key) => {
          const val = item[key];
          if (keys.includes(key)) {
            obj[parse[key]] = val;
          }
        });
        params.push(obj);
      });
      return params;
    },
  },
  mounted() {
    this.$emit("clear", this.$refs.uploadXlsx);
  },
};
</script>
  
  <style lang="scss" scoped>
</style>
  